package com.by.wx.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
import com.by.common.conf.WxConfMager;
import com.by.common.cont.WxConst;
import com.by.common.util.MD5Utils;
import com.by.common.util.ThreadLocalDateUtil;
import com.by.common.vo.PhoneRoomResult;
import com.by.wx.entity.PhoneMember;
import com.by.wx.entity.SysEquipmentOperate;
import com.by.wx.entity.WxUser;
import com.by.wx.service.WxinService;
import com.by.wx.util.Util;

import net.sf.json.JSONObject;

//ok
@Controller
@RequestMapping("/wx/")
public class WxinController {

	public static Log log = LogFactory.getLog(WxinController.class);

	@Autowired
	private WxinService wxinService;

	@RequestMapping("idex")
	public String idex() {
		return "index";
	}

	// @RequestMapping("wxroomconl")
	// public String wxroomconl(){
	//// //local
	//// return "wxin/room_col";
	// //cluster
	// return "wxin/wx_smart";
	// }
	@RequestMapping("wxverify")
	public String wxverify() {
		return "wxin/wx_verify_phone_number";
	}

	@RequestMapping("smart")
	public String smart() {
		return "wxin/wx_smart";
	}

	// TODO test
	@RequestMapping("findOperationByEquipmentId")
	@ResponseBody
	public List<SysEquipmentOperate> findOperationByEquipmentId(Integer deviceId) {
		return wxinService.findOperationByEquipmentId(deviceId);
	}

	@RequestMapping("jumpSuccessToRoomController")
	public ModelAndView jumpSuccessToRoomController() {
		Session session = SecurityUtils.getSubject().getSession();
		// String renterId = (String) session.getAttribute("renter_id");
		// String roomId = (String) session.getAttribute("room_id");
		// String timestamp = (String) session.getAttribute("timestamp");
		// String sign = (String) session.getAttribute("sign");
		String url = WxConfMager.getProperty(WxConst.WXHTTP_OFFICIAL_CLUSTER_JUMP_ROOM_CONTROLLER_PAGE);
		if ("/".equals(url.substring(url.length() - 1))) {
		} else {
			url = url + "/";
		}
		return new ModelAndView("redirect:" + url);
		// return
		// "redriect:"+url+"renter_id="+renterId+"room_id="+roomId+"timestamp="+timestamp+"sign="+sign;
	}

	@RequestMapping("pcode")
	public String pcode() {
		int a = 0;
		if (a == 0) {
			return "wxin/wx_verify_phone_number";
		} else {
			for (int i = 0; i < 10; i++) {
				// System.out.println(i);
				return "wxin/verify_phone_number";
			}
		}
		return null;

	}

	@RequestMapping("wxPheMemReg")
	public String wxPheMemReg() {
		// return "http://baidu.com";
		return "wxin/phone_member_from_regiest";
	}

	@RequestMapping("ttts")
	public String ttts() {
		return "wxin/no_room_control2";
	}

	@RequestMapping("getUserInfos")
	public String getUserInfo(Model m, HttpServletRequest request, HttpSession session)
			throws NumberFormatException, ParseException {
		String code = request.getParameter("code");
		// System.out.println(code);
		String url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_ACCESS_TOKEN_URL_TEMPLATE);
		String appid = null;
		String secret = null;
		if (WxConfMager.getBoolean(WxConst.WX_OFFICIAL_TEST_LOCAL)) {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPSECRET);
		} else {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPSECRET);
		}
		url = url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
		String result = Util.get(url);
		// System.out.println(result);
		String at = JSONObject.fromObject(result).getString("access_token");
		String openid = JSONObject.fromObject(result).getString("openid");
		// JSONObject json = (JSONObject)JSON.parse(result);
		// String at = (String) json.get("access_token");
		// String openid = (String) json.get("openid");

		url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_SNSAPI_USERINFO_URL_TEMPLATE);
		url = url.replace("ACCESS_TOKEN", at).replace("OPENID", openid);
		result = Util.get(url);
		// System.out.println(result);
		JSONObject js = JSONObject.fromObject(result);
		log.info("weixin---json::" + js);
		// System.out.println(js);
		// Map<String, Object> resultMap = (Map<String, Object>)
		// JSONObject.parse(js.toString());
		// JSONArray js = JSONArray.fromObject(result);
		// System.out.println(js);
		// m.addAttribute("res",resultMap);
		// session.setAttribute("res", js);
		session.setAttribute("openid", openid);
		String nickname = JSONObject.fromObject(result).getString("nickname");
		session.setAttribute("nickname", nickname);
		String sex = JSONObject.fromObject(result).getString("sex");
		m.addAttribute("nickname", nickname);
		m.addAttribute("sex", sex);
		m.addAttribute("openid", openid);

		// member
		List<PhoneMember> flagRoomVerf = wxinService.findPrivilegeByOpenidVerifyToSkipHref(openid);
		if (flagRoomVerf.size() == 0) {
			// System.out.println("noresult");
			log.info("此openid" + openid + "是没注册新用户");
			return "wxin/ft_verify_phone_number";
		} else {
			// wx regiest
			Integer flagRoomConditionId = flagRoomVerf.get(0).getVipId();
			// inner join
			List<PhoneRoomResult> AllRoomLogs = wxinService.findCheckRoomLineById(flagRoomConditionId);
			String roomNum = null;
			for (PhoneRoomResult res : AllRoomLogs) {
				if (StringUtils.isEmpty(res.getEnd())) {
					roomNum = res.getRoomNumber();
				}
			}
			if (StringUtils.isEmpty(roomNum)) {
				return "wxin/no_room_control";
			} else {
				String rod = flagRoomVerf.get(0).getCoded();

				if (StringUtils.isEmpty(rod)) {
					// update code
					return "wxin/wx_verify_phone_number";
				} else {
//					Date date = new Date();
//					long compNow = date.getTime();
//					long yesterFlagTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[0]+"-"+ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[1]+"-"
//							+(String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])-1).length()==1? "0"+String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])-1):String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])-1))
//							+" "+TelConfMager.getProperty(TelConst.HOTOL_EXPIRATION_TIME_LIMITED_HOURS_MINUTES_SECONDS)).getTime();
//					long tomoFlagTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[0]+"-"+ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[1]+"-"
//							+(String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])+1).length()==1? "0"+String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])+1):String.valueOf(Integer.parseInt(ThreadLocalDateUtil.formatDate(date).split(" ")[0].split("-")[2])+1))
//							+" "+TelConfMager.getProperty(TelConst.HOTOL_EXPIRATION_TIME_LIMITED_HOURS_MINUTES_SECONDS)).getTime();
//					long nowFlagTime = ThreadLocalDateUtil.parse(ThreadLocalDateUtil.formatDate(date).split(" ")[0]+" 12:00:00").getTime();
//					
//					long compTime = flagRoomVerf.get(0).getLastCodeTime().getTime();
					
//					if (yesterFlagTime<compNow && compNow <= nowFlagTime) {
//						// 未超时
//						return "wxin/room_col";
//					}else if (compNow>nowFlagTime && nowFlagTime<=tomoFlagTime) {
//						// 超时
//						wxinService.deletePhoMemberCodedByOpenid(openid);
//						return "wxin/verify_phone_number";
//					}else {
//						System.out.println("error");
//						return null;
//					}
					String phone = AllRoomLogs.get(0).getPhone();
					String username = AllRoomLogs.get(0).getUsername();
					m.addAttribute("phone", phone);
					m.addAttribute("username", username);

					String date = ThreadLocalDateUtil.formatDate(new Date());
					Integer rid = AllRoomLogs.get(0).getVipId();
					String sign = MD5Utils.generateMD5SignString(String.valueOf(rid), roomNum, date);

					session.setAttribute("timestamp", date);
					session.setAttribute("renter_id", rid);
					session.setAttribute("room_id", roomNum);
					session.setAttribute("sign", sign);

					// Timestamp timestamp = Timestamp.valueOf(ThreadLocalDateUtil.formatDate(ThreadLocalDateUtil.parse(date)));
					// wxinService.updateSessionTimeSignByOpenid(timestamp,sign,openid);
					// return "wxin/room_col";
					// TODO
					return "wxin/wxsuccess";
				}
				// return "wxin/verify_phone_number";
			}
			
		}
		// if(openid == null){
		// return "wxin/no_room_control";
		// }else{
		// return "wxin/verify_phone_number";
		// }
	}

	@RequestMapping("wxinRegiest")
	public String wxinRegiest(Model m, HttpServletRequest request, HttpSession session) {
		String code = request.getParameter("code");
		String url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_ACCESS_TOKEN_URL_TEMPLATE);
		String appid = null;
		String secret = null;
		if (WxConfMager.getBoolean(WxConst.WX_OFFICIAL_TEST_LOCAL)) {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPSECRET);
		} else {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPSECRET);
		}
		url = url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
		String result = Util.get(url);
		String at = JSONObject.fromObject(result).getString("access_token");
		String openid = JSONObject.fromObject(result).getString("openid");

		url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_SNSAPI_USERINFO_URL_TEMPLATE);
		url = url.replace("ACCESS_TOKEN", at).replace("OPENID", openid);
		result = Util.get(url);
		JSONObject js = JSONObject.fromObject(result);
		log.info("该openid为" + openid + "是从酒店注册菜单点击进来的json：" + js);
		session.setAttribute("openid", openid);
		String nickname = JSONObject.fromObject(result).getString("nickname");
		session.setAttribute("nickname", nickname);
		String sex = JSONObject.fromObject(result).getString("sex");
		m.addAttribute("nickname", nickname);
		m.addAttribute("sex", sex);
		m.addAttribute("openid", openid);

		return "wxin/index_phone_regiest";
	}

	@RequestMapping("findListTest")
	@ResponseBody
	public List<PhoneMember> findListTest(String openid) {
		List<PhoneMember> flagRoomVerf = wxinService.findPrivilegeByOpenidVerifyToSkipHref(openid);
		if (flagRoomVerf.size() == 0) {
			// return "wxin/verify_phone_number";
			return flagRoomVerf;
		} else {
			Integer flagRoomConditionId = flagRoomVerf.get(0).getVipId();
			// System.out.println(flagRoomConditionId);
			List<PhoneRoomResult> AllRoomLogs = wxinService.findCheckRoomLineById(flagRoomConditionId);
			String roomNum = null;
			for (PhoneRoomResult res : AllRoomLogs) {
				if (StringUtils.isEmpty(res.getEnd())) {
					roomNum = res.getRoomNumber();
				}
			}
			if (StringUtils.isEmpty(roomNum)) {
				// System.out.println("wxin/no_room_control");
			} else {
				// System.out.println("wxin/verify_phone_number");
			}
			// System.out.println(roomNum);
			return flagRoomVerf;
		}
	}

	@RequestMapping("getUserInfoo")
	@ResponseBody
	public String getUserInfoo(HttpServletRequest request) {
		String code = request.getParameter("code");
		String url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_ACCESS_TOKEN_URL_TEMPLATE);
		String appid = null;
		String secret = null;
		if (WxConfMager.getBoolean(WxConst.WX_OFFICIAL_TEST_LOCAL)) {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPSECRET);
		} else {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPSECRET);
		}
		url = url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
		String result = Util.get(url);
		String openid = JSONObject.fromObject(result).getString("openid");
		return openid;
	}
	
	@RequestMapping("testmodel")
	public String testmodel(Model m){
		String iurl = "http:\\/\\/thirdwx.qlogo.cn\\/mmopen\\/vi_32\\/Q0j4TwGTfTI1LvZeAvSxQdsP2aic2oYCD0B0MOg4v5x6QX69trXNRBo7VcLsX0x03GMOvBl0THkySMD0N2sZ5MQ\\/132";
		String result = "{'openid':'okKyr1U4WX5GbxJtvK01uDAwHXiM','nickname':'wegigbalebykillofy','sex':1,'language':'zh_CN','city':'广州','province':'广东','country':'中国','headimgurl':'"+iurl+"','privilege':[]}";
		// System.out.println(result);
		List<WxUser> list = new ArrayList<>();
		WxUser wu = new WxUser();
		String reses = result.replace("{", "").replace("}", "").replace("\'", "");
		String[] resr = reses.split(",");
		for (int i = 0; i < resr.length; i++) {
			if ("openid".equals(resr[i].split(":")[0])) {
				wu.setOpenid(resr[i].split(":")[1]);
			} else if ("nickname".equals(resr[i].split(":")[0])) {
				wu.setNickname(resr[i].split(":")[1]);
			} else if ("sex".equals(resr[i].split(":")[0])) {
				wu.setSex(resr[i].split(":")[1]);
			} else if ("language".equals(resr[i].split(":")[0])) {
				wu.setLanguage(resr[i].split(":")[1]);
			} else if ("city".equals(resr[i].split(":")[0])) {
				wu.setCity(resr[i].split(":")[1]);
			} else if ("province".equals(resr[i].split(":")[0])) {
				wu.setProvince(resr[i].split(":")[1]);
			} else if ("country".equals(resr[i].split(":")[0])) {
				wu.setCountry(resr[i].split(":")[1]);
			} else if ("headimgurl".equals(resr[i].split(":")[0])) {
				wu.setHeadimgurl(resr[i].split(":")[1]);
			}
		}
		// JSONObject json = (JSONObject)JSON.parse(result);
		// Map<String, Object> resultMap = (Map<String, Object>)
		// JSONObject.parse(json.toString());
		// System.out.println(json);
		list.add(wu);
		// System.out.println(list);
		// m.addAttribute("res",list);
		JSONObject json = JSONObject.fromObject(result);
		m.addAttribute("res", json);
		String sex = "male";
		m.addAttribute("sex", sex);
		return "testmodel";
	}

	@RequestMapping("wexinlogin")
	public String wxlogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_CODE_URL_TEMPLATE);
		String appid = null;
		String redirect_url = null;
		String scope = WxConfMager.getProperty(WxConst.WXWEB_SNSAPI_BASEUSERINFO);
		if (WxConfMager.getBoolean(WxConst.WX_OFFICIAL_TEST_LOCAL)) {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPID);
			redirect_url = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_REDIRECT_URI)
					+ WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_REDIRECT_URI_SUFFIX);
		} else {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPID);
			redirect_url = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_REDIRECT_URI)
					+ WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_REDIRECT_URI_SUFFIX);
		}
		url = url.replace("APPID", appid).replace("REDIRECT_URI", redirect_url).replace("SCOPE", scope);
		// System.out.println(url);
		return url;
	}

	@RequestMapping("doWxAccToken")
	public String doWxAccToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter("code");
		String url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_ACCESS_TOKEN_URL_TEMPLATE);
		// System.out.println(url);
		String appid = null;
		String secret = null;
		if (WxConfMager.getBoolean(WxConst.WX_OFFICIAL_TEST_LOCAL)) {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_TEST_APPSECRET);
		} else {
			appid = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPID);
			secret = WxConfMager.getProperty(WxConst.WX_OFFICIAL_CLUSTER_APPSECRET);
		}
		url = url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
		String result = Util.get(url);
		log.info("doWxAccToken.do中的json串=" + result);
		// System.out.println(result);
		// String at = JSONObject.fromObject(result).getString("access_token");
		// String openid = JSONObject.fromObject(result).getString("openid");
		// System.out.println("a="+at);
		// System.out.println("o="+openid);

		url = WxConfMager.getProperty(WxConst.WXWEB_OFFICIAL_GET_SNSAPI_USERINFO_URL_TEMPLATE);
		// System.out.println(url);
		// url = url.replace("ACCESS_TOKEN", at).replace("OPENID", openid);
		result = Util.get(url);
		// System.out.println(result);
		return "indexpa";
	}

}
